package dynamicprogramming;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/5 15:37
 * https://leetcode-cn.com/problems/coin-change/
 */
public class CoinChange {

    /**
     * dp[j]表示凑出金额j所需的最少物品个数
     * 递推公式：dp[j] = Math.min(dp[j], dp[j - nums[i]] + 1)
     * 初始化：dp[1...amount] = Integer.Max_VALUE;
     * @param coins
     * @param amount
     * @return
     */
    public static int coinChange(int[] coins, int amount) {
        int[] dp = new int[amount + 1];
        for (int i = 1; i < dp.length; i++) {
            dp[i] = Integer.MAX_VALUE;
        }
        for (int i = 0; i < coins.length; i++) {
            for (int j = coins[i]; j <= amount; j++) {
                if (dp[j - coins[i]] != Integer.MAX_VALUE) {
                    dp[j] = Math.min(dp[j], dp[j - coins[i]] + 1);
                }
            }
        }
        if (dp[amount] == Integer.MAX_VALUE) {
            return -1;
        }
        return dp[amount];
    }

    public static void main(String[] args) {
        int[] coins = {1, 2, 5};
        int amount = 11;
        System.out.println(coinChange(coins, amount));

    }
}
